package com.atgugu.flink.chapter11;

import com.atgugu.flink.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.GroupWindow;
import org.apache.flink.table.api.Session;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.lit;

/**
 * @Author lzc
 * @Date 2022/4/11 9:12
 */
public class Flink15_Window_Group {
    public static void main(String[] args) {
        // 流->动态表->连续查询->动态表->流
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        SingleOutputStreamOperator<WaterSensor> stream = env
            .fromElements(
                new WaterSensor("sensor_1", 1001L, 1),
                new WaterSensor("sensor_1", 3000L, 3),
                new WaterSensor("sensor_1", 4000L, 4),
                new WaterSensor("sensor_2", 2000L, 2),
                new WaterSensor("sensor_2", 5000L, 5),
                new WaterSensor("sensor_1", 6001L, 6)
            )
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((ws, ts) -> ws.getTs())
            );
        
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        Table table = tEnv.fromDataStream(stream, $("id"), $("ts").rowtime(), $("vc"));
        
        
        // 每隔5s,统计最近5s内每个id的水位和
        // select id, w, sum(vc) from t group by id, w
//        GroupWindow w = Tumble.over(lit(5).second()).on($("ts")).as("w");
//        GroupWindow w = Slide.over(lit(5).second()).every(lit(2).second()).on($("ts")).as("w");  // 滑动窗口
        GroupWindow w = Session.withGap(lit(2).second()).on($("ts")).as("w");
        
        table
            .window(w)
            .groupBy($("id"), $("w"))
            .select($("id"), $("vc").sum().as("vc_sum"), $("w").start().as("stt"), $("w").end().as("edt"))
            .execute()
            .print();
        
        
    }
}
